package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.PageUtil;
import cn.stylefeng.guns.sys.modular.system.db4.service.TeamService;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.ProjectTaskEnum;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.RoleIdEnum;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.AreaParam;
import cn.stylefeng.guns.sys.modular.system.model.params.ProjectParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskFlowParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskStatusParam;
import cn.stylefeng.guns.sys.modular.system.model.result.ProjectResult;
import cn.stylefeng.guns.sys.modular.system.model.result.TaskResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.guns.sys.modular.system.service.impl.ProjectServiceImpl;
import cn.stylefeng.guns.sys.modular.system.service.impl.TaskStatusServiceImpl;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 工程h5端
 */
@CrossOrigin
@Controller
@RequestMapping("/gcH5")
public class GcH5Controller {

    private static Logger log = LoggerFactory.getLogger(GcH5Controller.class);
    @Resource
    private TaskStatusService taskStatusService;
    @Resource
    private TaskService taskService;
    @Resource
    private TaskStatusMapper taskStatusMapper;
    @Resource
    private TeamService teamService;
    @Resource
    private MouldBoardMsgMapper mouldBoardMsgMapper;
    @Resource
    private ProjectService projectService;
    @Resource
    private UserService userService;
    @Resource
    private MouldBoardMsgService mouldBoardMsgService;
    @Resource
    private TaskFlowService taskFlowService;

    @Resource
    private ProjectServiceImpl projectServiceImpl;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private BtyWxMapper btyWxMapper;

    @Resource
    private BtyWxService btyWxService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private GcgMsgMapper gcgMsgMapper;
    @Resource
    private GzhConfig gzhConfig;
    @Resource
    private TaskStatusServiceImpl taskStatusServiceImpl;
    @Resource
    private AreaService areaService;
    @Resource
    private RoleService roleService;
    @Resource
    private GcgMsgMapper msgMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private BtyTxlMapper btyTxlMapper;

    // 跳转URL
    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
    private String type = "&response_type=code";
    private String scope = "&scope=snsapi_userinfo";
    private String state = "&state=STATE#wechat_redirect";


    private final int enable = 1;
    private final int disable = 0;

    /**
     * 根据type查找所有对应层级的区域
     */
    @GetMapping(value = "/getAreaByType")
    @ResponseBody
    public ResponseData getAreaByType(HttpServletRequest request) {
        String type = request.getParameter("type");
        AreaParam areaParam = new AreaParam();
        if (ToolUtil.isNotEmpty(type)) {
            areaParam.setType(Integer.parseInt(type));
        }
        List<Area> areaList = this.areaService.getAreaByType(areaParam);
        return ResponseData.success(areaList);
    }

    /**
     * 根据pid查找所有对应的子级区域
     */
    @GetMapping(value = "/getAreaByPid")
    @ResponseBody
    public ResponseData getAreaByPid(AreaParam areaParam) {
        List<Area> areaList = this.areaService.getAreaByPid(areaParam);
        return ResponseData.success(areaList);
    }

    /**
     * 批量开店或者闭店
     *
     * @param ids    工程id
     * @param status 闭店 status=0 开店status=1
     * @return
     */
    @RequestMapping("/openOrClose")
    @ResponseBody
    public ResponseData openOrClose(String ids, Integer status, HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        //工程总监
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();
        //开发总监
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();
        //营运总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();
        //获取用户角色
        User user = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(user)) {
            String[] roles = user.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        if (roleList.contains(role_gczj) | roleList.contains(role_kfzj) | roleList.contains(role_yyzj)) {
            Integer taskId=0;
            if(roleList.contains(role_gczj)){
                taskId=5;
            }else if(roleList.contains(role_kfzj)){
                taskId=6;
            }else if(roleList.contains(role_yyzj)){
                taskId=7;
            }
            String id[] = ids.split(",");
            for (int i = 0; i < id.length; i++) {
                this.projectService.editBatch(id[i], status);
                taskStatusMapper.editBatch(id[i],status,taskId);
            }
        } else {
            return ResponseData.error(501, "没有权限");
        }

        return ResponseData.success();
    }

    @GetMapping(value = "/accessCheckByPhone")
    @ResponseBody
    public ResponseData accessCheckByPhone(HttpServletRequest request) {
        String phone = request.getParameter("phone");
//        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        //开发人员角色
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();
        //获取用户信息
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        } else {
            return ResponseData.error(502, "查不到用户信息");
        }
        //开发人员角色可以新增商务工程条件
        if (roleList.contains(role_kfry)) {
            return ResponseData.success();
        } else {
            return ResponseData.error(501, "没有权限新增");
        }
    }

    /**
     * 获取用户的角色列表
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/userAccess")
    @ResponseBody
    public ResponseData userAccess(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        Map<String, Object> map = new HashMap<>();
        List<String> roleList = new ArrayList<>();
        //获取用户信息
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                Role role1 = roleService.getById(role);
                if (ToolUtil.isNotEmpty(role1)) {
                    roleList.add(role1.getName());
                }
            }
            map.put("roleList", roleList);
        } else {
            return ResponseData.error(502, "查不到用户信息");
        }
        return ResponseData.success(map);

    }


    /**
     * 工程列表
     *
     * @param param
     * @return
     */
    @GetMapping(value = "/list")
    @ResponseBody
    public ResponseData list(ProjectParam param, HttpServletRequest request) throws Exception {
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        String phones = request.getParameter("phone");
        int page = Integer.parseInt(request.getParameter("page") == null ? "0" : request.getParameter("page"));//相当于pageNo
        int limit = Integer.parseInt(request.getParameter("limit") == null ? "0" : request.getParameter("limit"));//相当于pageSize
        List<Long> roleList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        ProjectResult result = new ProjectResult();
        //获取用户角色
        User user = userService.getAccount(phones);
        Long userId;
        if (ToolUtil.isNotEmpty(user)) {
            userId = user.getUserId();
            String[] roles = user.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
//            if (ToolUtil.isEmpty(param.getAllStautusEnd())) {
//                param.setAllStautusEnd("N");
//            }
//            if (ToolUtil.isEmpty(param.getStatus())) {
//                param.setStatus(1);
//            }

            if (ToolUtil.isNotEmpty(param.getId())) {
                param.setId(param.getId());
            }
            Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
            Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
            Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
            Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();//开发人员
            Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();//营运经理
            Long role_dd = RoleIdEnum.ROLE_DD.getCode();//督导
            Long role_netshop = RoleIdEnum.ROLE_NETSHOP.getCode();//网上建店负责人
            Long role_klj = RoleIdEnum.ROLE_KELEJI.getCode();//可乐机负责人
            Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();//工程部
            Long role_syda = RoleIdEnum.ROLE_SYDA.getCode();//收银档案负责人
            String phone = phones;
            String jiedian = param.getJiedian();

            param.setJdsj_px("0");
            if (roleList.size() > 0) {
                List<Integer> taskByRole = taskStatusService.getTaskByRole(roleList);
                param.setTaskids(StringUtils.join(taskByRole, ","));
            }


            if (roleList.contains(role_kfry)&&!roleList.contains(role_kfzj)) {
                param.setCreateUser(userId);
            }
            if (roleList.contains(role_yyjl)) {
                param.setYyjl(phone);
            }
            if (roleList.contains(role_dd)) {
                param.setDd(phone);
            }
            if (ToolUtil.isNotEmpty(jiedian)) {
                param.setJiedian(jiedian);
            }


            List<ProjectResult> lists = projectService.h5List(param);

            //List<ProjectResult> listss = new ArrayList<>();
            System.out.println("list.size:" + lists.size());
            if(lists.size()>100){
                lists=lists.subList(0,80);
            }
            List<ProjectResult> records = lists;
            Integer count = 0;
            taskService.setProcessSteps(records);
            List<TaskResult> listIds = taskService.listIdsByRoleIds(String.join(",", role_kfry.toString(), role_gczj.toString(), role_kfzj.toString()));
            Map<Long, String> roleIdTaskIds = listIds.stream().collect(Collectors.toMap(TaskResult::getRoleId, TaskResult::getIds));
            //获取开发人员任务完成情况
            String kf_taskids = roleIdTaskIds.get(role_kfry);
            String gczj_taskids = roleIdTaskIds.get(role_gczj);
            String kfzj_taskids = roleIdTaskIds.get(role_kfzj);
            //所有taskStatus信息
            List<TaskStatus> taskStatusList = taskStatusService.listTaskStatus();
            Map<Integer, List<TaskStatus>> taskStatusProIdMap = taskStatusList.stream().collect(Collectors.groupingBy(TaskStatus::getProId));
            List<TaskStatus> rejects = taskStatusService.listReject();
            Map<String, TaskStatus> rejectMap = rejects.stream().collect(Collectors.toMap(k -> k.getProId() + "_" + k.getTaskId(), Function.identity()));
            Date curtDate = new Date();
            List<Map> maps = teamService.selectYyjlList();
            Map<Object, Object> yyjlmap = maps.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("yyjl")));
            List<Map> maps2 = teamService.selectDdListAll();
            Map<Object, Object> ddmap = maps2.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("dd")));
            Iterator<ProjectResult> iterator = records.iterator();

//            for (int i = 0; i <records.size(); i++) {
//                ProjectResult rs=records.get(i);
//            }
            while (iterator.hasNext()) {
                ProjectResult rs = iterator.next();
                Integer proid = rs.getId();
                Map<String, String> openidMap = projectService.selectDd(proid);
                if (ToolUtil.isNotEmpty(openidMap)) {
                    rs.setYyjlname(openidMap.get("yyName"));
                    rs.setDdname(openidMap.get("ddName"));
                }
//                ProjectParam param1=new ProjectParam();
//                param1.setId(proid);
//                String swtj=projectMapper.swtj(param1);
//                rs.setSwtj(swtj);
//                String gctj=projectMapper.gctj(param1);
//                rs.setGctj(gctj);
                List<TaskStatus> listStatus = taskStatusService.list(new QueryWrapper<TaskStatus>().eq("pro_id", proid)
                        .eq("task_id", 6).ne("status", 0));
                if (listStatus.size() > 0) {
                    rs.setSwtj("已填");
                } else {
                    rs.setSwtj("");
                }
                List<TaskStatus> listStatuss = taskStatusService.list(new QueryWrapper<TaskStatus>().eq("pro_id", proid)
                        .eq("task_id", 5).ne("status", 0));
                if (listStatuss.size() > 0) {
                    rs.setGctj("已填");
                } else {
                    rs.setGctj("");
                }

                //获取营运经理完成情况
                String allotDd = rs.getAllotDd();
                String gcb = rs.getGcb();
                String dudao = rs.getDudao();
                if (ToolUtil.isNotEmpty(allotDd) && allotDd.equals("已指定督导")) {
                    rs.setYyjlFinish(true);
                }
//                //获取工程部任务是否完成
//                if (ToolUtil.isNotEmpty(gcb) && gcb.equals("工程已完工")) {
//                    rs.setGcbFinish(true);
//                }
                //获取督导任务是否完成
                if (ToolUtil.isNotEmpty(dudao) && dudao.equals("督导任务完成")) {
                    rs.setDdFinish(true);
                }

                //根据角色获取任务ids
                boolean kfry_ts = isexist2(taskStatusProIdMap.get(proid), kf_taskids);
                rs.setKfryFinish(kfry_ts);

                //获取工程总监任务完成情况
                boolean gczj_ts = isexist2(taskStatusProIdMap.get(proid), gczj_taskids);
                rs.setGczjFinish(gczj_ts);
                //获取开发总监任务完成情况
                boolean kfzj_ts = isexist2(taskStatusProIdMap.get(proid), kfzj_taskids);
                rs.setKfzjFinish(kfzj_ts);
                //获取营运总监审核
                boolean yyzj_ts = isexist2(taskStatusProIdMap.get(proid), "7");

                boolean zdYyjl=isexist2(taskStatusProIdMap.get(proid), "40");
                 if(yyzj_ts&&zdYyjl){
                     rs.setYyzjFinish(true);
                 }

                //yyzj已确认
                if (yyzj_ts) {
                    //是否确认开工日期
                    rs.setKgtime("开工日期未确定");
                    String kaigong = "32";
//                boolean kaigong_ts = isexist(proid, kaigong);
                    List<TaskStatus> listts = getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid), kaigong);
                    rs.setGckg(enable);
                    if (ToolUtil.isNotEmpty(listts)) {
                        long num = DateUtil.getDaysNum(listts.get(0).getContent(), DateUtil.getNowDate());
                        if (num < 0) {
                            rs.setKgtime("开工日期：" + listts.get(0).getContent());
                        } else {
                            //判断工程是否完成
                            List<TaskStatus> list = getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid), "34");
                            if (list.size() > 0) {
                                String finiDate = list.get(0).getContent();
                                if (ToolUtil.isNotEmpty(finiDate)) {
                                    Date finDate = DateUtil.getDateByStr(finiDate);
                                    if (finDate.before(curtDate)) {
                                        rs.setKgtime("已完工");
                                    } else {
                                        rs.setKgtime("已开工" + num + "天");
                                    }
                                } else {
                                    rs.setKgtime("");
                                }
                            } else {
                                rs.setKgtime("已开工" + num + "天");
                            }
                        }
                    }
                    if (roleList.contains(role_yyzj)) {//营运总监
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                        rs.setSelectyyjl(enable);

                        //获取工程部任务是否完成
                        if (ToolUtil.isNotEmpty(gcb) && gcb.equals("工程已完工")) {
                            rs.setGcbFinish(true);
                        }
                        //获取工程部任务是否完成
//                    ProjectParam projectParam = new ProjectParam();
//                    projectParam.setId(proid);
//                    count = projectService.gcbFinish(projectParam);
//                    if (count > 0) {
//                        rs.setGcbFinish(true);
//                }

                        if (ToolUtil.isNotEmpty(rs.getYyjl())) {
                            rs.setYyjlname(String.valueOf(yyjlmap.get(rs.getYyjl()) == null ? "无名" : yyjlmap.get(rs.getYyjl())));
                        }
                        if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(rs.getDd())) {
                            rs.setKdtask(enable);//开店任务
                        }
                    }
                    if (roleList.contains(role_yyjl)) {//营运经理
                        ProjectParam projectParam = new ProjectParam();
                        projectParam.setId(proid);
                        count = projectService.gcbFinish(projectParam);
                        if (count > 0) {
                            rs.setGcbFinish(true);
                        }
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                        rs.setSelectdd(enable);
                        if (ToolUtil.isNotEmpty(rs.getDd())) {
                            rs.setDdname(String.valueOf(ddmap.get(rs.getDd()) == null ? "无名" : ddmap.get(rs.getDd())));
                        }
                        if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(rs.getDd())) {
                            rs.setKdtask(enable);//开店任务
                        }
                    }
                    if (roleList.contains(role_dd)) {//督导

                        //获取工程部任务是否完成
                        if (ToolUtil.isNotEmpty(gcb) && gcb.equals("工程已完工")) {
                            rs.setGcbFinish(true);
                        }
//                        //获取督导任务是否完成
//                        if (ToolUtil.isNotEmpty(dudao) && dudao.equals("督导任务完成")) {
//                            rs.setDdFinish(true);
//                        }
//                        //获取督导任务是否完成
//                        ProjectParam projectParam = new ProjectParam();
//                        projectParam.setId(proid);
//                        Integer ddCount = projectService.ddFinish(projectParam);
//                        if (ddCount > 0) {
//                            rs.setDdFinish(true);
//                        }
//                        count = projectService.gcbFinish(projectParam);
//                        if (count > 0) {
//                            rs.setGcbFinish(true);
//                        }

                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                        if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(phone) && phone.equals(rs.getDd())) {
                            rs.setKdtask(enable);//开店任务
                            rs.setKdtaskedit(enable);//开店任务信息可否编辑
                        }
                    }
                    if (roleList.contains(role_kfry)) {//工程开发人员、
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                    }
                    if (roleList.contains(role_gczj)) {//工程总监
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                    }

                    if (roleList.contains(role_gcb)) {//工程部

                        //获取工程部任务是否完成
                        if (ToolUtil.isNotEmpty(gcb) && gcb.equals("工程已完工")) {
                            rs.setGcbFinish(true);
                        }
                        //获取工程部任务是否完成
//                        ProjectParam projectParam = new ProjectParam();
//                        projectParam.setId(proid);
//                        count = projectService.gcbFinish(projectParam);
//                        if (count > 0) {
//                            rs.setGcbFinish(true);
//                        }
                        rs.setGcbtn(enable);
                        rs.setGckgedit(enable);
                    }
                    //可乐机负责人
//                    if(roleList.contains(role_klj)){
//                        //获取可乐机负责人任务是否完成
//                        ProjectParam projectParam = new ProjectParam();
//                        projectParam.setId(proid);
//                        count = projectMapper.kljFinish(projectParam);
//                        if (count > 0) {
//                            rs.setKljFinish(true);
//                        }
//                    }
                    //收银档案负责人
//                    if(roleList.contains(role_syda)){
//                        //获取收银档案负责人任务是否完成
//                        ProjectParam projectParam = new ProjectParam();
//                        projectParam.setId(proid);
//                        count = projectMapper.syFinish(projectParam);
//                        if (count > 0) {
//                            rs.setSydaFinish(true);
//                        }
//                    }
                    //网上建店负责人
                    if (roleList.contains(role_netshop)) {
//                        //获取网上建店任务是否完成
//                        ProjectParam projectParam = new ProjectParam();
//                        projectParam.setId(proid);
//                        count = projectMapper.wsjdFinish(projectParam);
//                        if (count > 0) {
//                            rs.setWsjdFinish(true);
//                        }

                        if (ToolUtil.isNotEmpty(listts)) {
                            rs.setKdtask(enable);//开店任务
//                        rs.setKdtaskedit(enable);//开店任务信息可否编辑
                        }
                        //如果督导三个表格已完成，才能建店
                        Integer addrMouldid = 34;
                        Integer mealMouldid = 35;
                        Integer queuMouldid = 37;
                        List<MouldBoardMsg> addrlist = mouldBoardMsgMapper.getRecordByMould(addrMouldid);
                        List<MouldBoardMsg> meallist = mouldBoardMsgMapper.getRecordByMould(mealMouldid);
                        List<MouldBoardMsg> queuelist = mouldBoardMsgMapper.getRecordByMould(queuMouldid);
                        if (addrlist.size() > 0) {
                            //网上建店按钮
                            rs.setNetshopAddr(enable);
                        }
                        if (meallist.size() > 0) {
                            //线上套餐按钮
                            rs.setMealOnline(enable);
                        }
                        if (queuelist.size() > 0) {
                            //排队机按钮
                            rs.setQueueMachine(enable);
                        }
                    }

                    if (roleList.contains(role_kfzj)) {//开发总监
                        //商务条件按钮
                        rs.setSwbtn(enable);
                        //工程条件按钮
                        rs.setGcbtn(enable);

                    }
                } else if (gczj_ts && kfzj_ts) {//kfzj+gczj OK
                    if (roleList.contains(role_gczj) || roleList.contains(role_kfry)) {//工程总监/开发人员
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                    } else if (roleList.contains(role_yyzj)) {//营运总监
                        if (ToolUtil.isNotEmpty(rs.getYyzj()) && rs.getYyzj().contains("驳回")) {
                            rs.setGcbtn(-1);
                            TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_7.getCode());
                            rs.setYyRejectInfo(rej.getContent());
                        }
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "7");//营运总监确认taskid
                        if (!isexist) {
                            //商务条件审核按钮
                            rs.setAuditbtn(enable);
                        }
                    } else if (roleList.contains(role_kfzj)) {//开发总监
                        rs.setSwbtn(enable);
                        rs.setGcbtn(enable);
                    }
                } else if (kfry_ts) {//开发人员任务完成
                    if (roleList.contains(role_gczj)) {//工程总监
                        boolean isexist0 = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认
                        if (isexist0) {
                            rs.setSwbtn(enable);
                        } else {
                            rs.setSwbtn(2);
                        }
                        rs.setGcbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "5");//工程总监确认taskid
                        if (!isexist) {
                            //商务条件通过驳回按钮是否显示
                            rs.setAuditbtn(disable);
                            //工程条件通过驳回按钮是否显示
                            rs.setAuditbtn1(enable);
                        }
                    } else if (roleList.contains(role_kfzj)) {//开发总监

                        rs.setSwbtn(enable);
                        rs.setGcbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认taskid
                        if (!isexist) {
                            //商务条件通过驳回按钮是否显示
                            rs.setAuditbtn(enable);
                            //工程条件通过驳回按钮是否显示
                            rs.setAuditbtn1(disable);
                        }
                    } else if (roleList.contains(role_kfry)) {//开发人员
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                    } else if (roleList.contains(role_yyzj)) {//营运总监
                        rs.setSwbtn(enable);
                        rs.setGcbtn(enable);
                    }
                } else {
                    //kf人员未完成
                    boolean swisexist = isexist2(taskStatusProIdMap.get(proid), "3");//sw
                    boolean gcisexist = isexist2(taskStatusProIdMap.get(proid), "2");//gc
                    if (roleList.contains(role_kfry)) {//开发人员
                        rs.setGcbtn(enable);
                        rs.setSwbtn(enable);
                        if (!swisexist) {
                            //商务模板条件可否编辑
                            rs.setSwedit(enable);
                        }
                        if (!gcisexist) {
                            //工程模板条件可否编辑
                            rs.setGcedit(enable);
                        }

                    } else if (roleList.contains(role_kfzj)) {//开发总监
                        if (swisexist) {//店名和商务条件完成
                            rs.setSwbtn(enable);
                            boolean isexist = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认taskid
                            if (!isexist) {
                                //商务条件通过驳回按钮是否显示
                                rs.setAuditbtn(enable);
                            }
                        }
                        if (gcisexist) {
                            rs.setGcbtn(enable);
                        }
                    } else if (roleList.contains(role_yyzj)) {//营运总监
                        if (swisexist) {
                            rs.setSwbtn(enable);
                        }
                        if (gcisexist) {
                            rs.setGcbtn(enable);
                        }
                    }
                    if (ToolUtil.isNotEmpty(rs.getKfzj()) && rs.getKfzj().contains("驳回")) {

                        rs.setSwbtn(-1);
                        TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_6.getCode());
                        //rs.setRejectInfo("开发总监'" + rej.getCreateName() + "'已驳回,原因：" + rej.getContent());
                        rs.setSwRejectInfo(rej.getContent());

                    }
                    if (ToolUtil.isNotEmpty(rs.getGczj()) && rs.getGczj().contains("驳回")) {
                        rs.setGcbtn(-1);
                        TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_5.getCode());
                        rs.setRejectInfo(rej.getContent());
                    }
                    if (ToolUtil.isNotEmpty(rs.getYyzj()) && rs.getYyzj().contains("驳回")) {
                        rs.setGcbtn(-1);
                        TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_7.getCode());
                        rs.setYyRejectInfo(rej.getContent());
                    }
                }
                result.setGcbtn(rs.getGcbtn());
                result.setSwbtn(rs.getSwbtn());
                //System.out.println("gcbtn:"+result.getGcbtn());
                //System.out.println("swbtn:"+result.getSwbtn());

            }


            List<ProjectResult> listKfry = new ArrayList<>();
            List<ProjectResult> listKfzj = new ArrayList<>();
            List<ProjectResult> listGczj = new ArrayList<>();
            List<ProjectResult> listYyzj = new ArrayList<>();
            List<ProjectResult> listGcb = new ArrayList<>();
            List<ProjectResult> listDd = new ArrayList<>();
            List<ProjectResult> listYyjl = new ArrayList<>();
            List<ProjectResult> listWsjd = new ArrayList<>();
            List<ProjectResult> listKlj = new ArrayList<>();
            List<ProjectResult> listSyda = new ArrayList<>();


            // 同时包含"营运经理","工程部","工程开发人员" 这三个角色的已完成列表
            if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry) && roleList.contains(role_yyjl) && roleList.contains(role_gcb)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(true)) {
                        listKfry.add(record);
                    }
                    if(record.getYyjlFinish().equals(true)){
                        listKfry.add(record);
                    }
                    listKfry=listKfry.stream().distinct().collect(Collectors.toList());
//                    if(record.getYyjlFinish().equals(false)){
//                        listKfry.remove(record);
//                    }
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
            }
            // 同时包含"营运经理","工程部","工程开发人员" 这三个角色的未完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry) && roleList.contains(role_yyjl) && roleList.contains(role_gcb)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(false)) {
                        listKfry.add(record);
                    }
                    if(record.getYyjlFinish().equals(false)&&record.getKfryFinish().equals(false)){
                        listKfry.add(record);
                    }
                    listKfry=listKfry.stream().distinct().collect(Collectors.toList());
                }

                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
            }

            // 同时包含"营运经理","工程开发人员" 这两个角色的已完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry) && roleList.contains(role_yyjl)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(true)) {
                        listKfry.add(record);
                    }
                    if (record.getYyjlFinish().equals(true)) {
                        listKfry.add(record);
                    }
                    listKfry=listKfry.stream().distinct().collect(Collectors.toList());
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
            }
            // 同时包含"营运经理","工程开发人员" 这两个角色的未完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry) && roleList.contains(role_yyjl)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(false)) {
                        listKfry.add(record);
                    }
                    if(record.getYyjlFinish().equals(false)&&record.getKfryFinish().equals(false)){
                        listKfry.add(record);
                    }
                    listKfry=listKfry.stream().distinct().collect(Collectors.toList());
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
            }

            // 同时包含"督导","工程开发人员" 这两个角色的已完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry) && roleList.contains(role_dd)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(true)) {
                        listKfry.add(record);
                    }
                    if (record.getDdFinish().equals(true)) {
                        listKfry.add(record);
                    }
                    listKfry=listKfry.stream().distinct().collect(Collectors.toList());
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
            }
            // 同时包含"督导","工程开发人员" 这两个角色的未完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry) && roleList.contains(role_dd)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(false)) {
                        listKfry.add(record);
                    }
                    if(record.getDdFinish().equals(false)&&record.getKfryFinish().equals(false)){
                        listKfry.add(record);
                    }
                    listKfry=listKfry.stream().distinct().collect(Collectors.toList());
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
            }

            //开发人员已完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(true)) {
                        listKfry.add(record);
                    }
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
                //开发人员未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry)) {
                for (ProjectResult record : records) {
                    if (record.getKfryFinish().equals(false)) {
                        listKfry.add(record);
                    }
                }
                count = listKfry.size();
                map.put("list", PageUtil.list(page, limit, listKfry));
                map.put("count", count);
                //开发总监已完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfzj)) {
                for (ProjectResult record : records) {
                    if (record.getKfzjFinish().equals(true)) {
                        listKfzj.add(record);
                    }
                }
                count = listKfzj.size();
                map.put("list", PageUtil.list(page, limit, listKfzj));
                map.put("count", count);
                //开发总监未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfzj)) {
                for (ProjectResult record : records) {
                    if (record.getKfzjFinish().equals(false)) {
                        listKfzj.add(record);
                    }
                }
                count = listKfzj.size();
                map.put("list", PageUtil.list(page, limit, listKfzj));
                map.put("count", count);
                //工程总监已完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_gczj)) {
                //Collections.frequency(records,);
                for (ProjectResult record : records) {
                    if (record.getGczjFinish().equals(true)) {
                        listGczj.add(record);
                    }
                }
                count = listGczj.size();
                map.put("list", listGczj);
                map.put("count", count);
                //工程总监未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_gczj)) {
                for (ProjectResult record : records) {
                    if (record.getGczjFinish().equals(false)) {
                        listGczj.add(record);
                    }
                }
                count = listGczj.size();
                map.put("list", PageUtil.list(page, limit, listGczj));
                map.put("count", count);
                //营运总监已完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_yyzj)) {
                for (ProjectResult record : records) {
                    if (record.getYyzjFinish().equals(true)) {
                        listYyzj.add(record);
                    }
                }
                count = listYyzj.size();
                map.put("list", PageUtil.list(page, limit, listYyzj));
                map.put("count", count);
                //营运总监未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_yyzj)) {
                for (ProjectResult record : records) {
                    if (record.getYyzjFinish().equals(false)) {
                        listYyzj.add(record);
                    }
                }
                count = listYyzj.size();
                map.put("list", PageUtil.list(page, limit, listYyzj));
                map.put("count", count);
                //工程部已完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_gcb)) {
                for (ProjectResult record : records) {
                    if (record.getGcbFinish().equals(true)) {
                        listGcb.add(record);
                    }
                }
                count = listGcb.size();
                map.put("list", PageUtil.list(page, limit, listGcb));
                map.put("count", count);
                //工程部未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_gcb)) {
                for (ProjectResult record : records) {
                    if (record.getGcbFinish().equals(false)) {
                        listGcb.add(record);
                    }
                }
                count = listGcb.size();
                map.put("list", PageUtil.list(page, limit, listGcb));
                map.put("count", count);
            }
            //督导已完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_dd)) {
                for (ProjectResult record : records) {
                    if (record.getDdFinish().equals(true)) {
                        listDd.add(record);
                    }
                }
                count = listDd.size();
                map.put("list", listDd);
                map.put("count", count);
                //督导未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_dd)) {
                for (ProjectResult record : records) {
                    if (record.getDdFinish().equals(false)) {
                        listDd.add(record);
                    }
                }
                count = listDd.size();
                map.put("list", PageUtil.list(page, limit, listDd));
                map.put("count", count);
            }
            //营运经理已完成列表
            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_yyjl)) {
                for (ProjectResult record : records) {
                    if (record.getYyjlFinish().equals(true)) {
                        listYyjl.add(record);
                    }
                }
                count = listYyjl.size();
                map.put("list", PageUtil.list(page, limit, listYyjl));
                map.put("count", count);
                //营运经理未完成列表
            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_yyjl)) {
                for (ProjectResult record : records) {
                    if (record.getYyjlFinish().equals(false)) {
                        listYyjl.add(record);
                    }
                }
                count = listYyjl.size();
                map.put("list", PageUtil.list(page, limit, listYyjl));
                map.put("count", count);
            }
//            //网上建店负责人已完成列表
//            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_netshop)) {
//                for (ProjectResult record : records) {
//                    if (record.getWsjdFinish().equals(true)) {
//                        listWsjd.add(record);
//                    }
//                }
//                count = listWsjd.size();
//                map.put("list", PageUtil.list(page, limit, listWsjd));
//                map.put("count", count);
//                //网上建店负责人未完成列表
//            } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_netshop)) {
//                for (ProjectResult record : records) {
//                    if (record.getWsjdFinish().equals(false)) {
//                        listWsjd.add(record);
//                    }
//                }
//                count = listWsjd.size();
//                map.put("list", PageUtil.list(page, limit, listWsjd));
//                map.put("count", count);
//            }
//            //可乐机负责人已完成列表
//            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_klj)) {
//                for (ProjectResult record : records) {
//                    if (record.getWsjdFinish().equals(true)) {
//                        listKlj.add(record);
//                    }
//                }
//                count = listKlj.size();
//                map.put("list", PageUtil.list(page, limit, listKlj));
//                map.put("count", count);
//            }
//            //可乐机负责人未完成列表
//            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_klj)) {
//                for (ProjectResult record : records) {
//                    if (record.getWsjdFinish().equals(false)) {
//                        listKlj.add(record);
//                    }
//                }
//                count = listKlj.size();
//                map.put("list", PageUtil.list(page, limit, listKlj));
//                map.put("count", count);
//            }

            //收银档案负责人已完成列表
//            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_syda)) {
//                for (ProjectResult record : records) {
//                    if (record.getWsjdFinish().equals(true)) {
//                        listSyda.add(record);
//                    }
//                }
//                count = listSyda.size();
//                map.put("list", PageUtil.list(page, limit, listSyda));
//                map.put("count", count);
//            }
//            //收银档案负责人未完成列表
//            else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_syda)) {
//                for (ProjectResult record : records) {
//                    if (record.getWsjdFinish().equals(false)) {
//                        listSyda.add(record);
//                    }
//                }
//                count = listSyda.size();
//                map.put("list", PageUtil.list(page, limit, listSyda));
//                map.put("count", count);
//            }

            else {
                map.put("list", PageUtil.list(page, limit, records));
                map.put("count", records.size());
                //return ResponseData.success(map);
            }

        } else {
            List list = new ArrayList();
            map.put("list", list);
            map.put("count", 0);
            //return ResponseData.success(map);
        }
        return ResponseData.success(map);


    }


    /**
     * 新增商务工程条件
     */
    @PostMapping(value = "/add")
    @ResponseBody
    public ResponseData add(@RequestBody String mouldBoardMsg, HttpServletRequest request) throws ParseException {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        //开发人员角色
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();
        //获取用户信息
        Long userId = null;
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            userId = users.getUserId();
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        //开发人员角色可以新增商务工程条件
        if (roleList.contains(role_kfry)) {
            List<MouldBoardMsg> mouldBoardMsgs = JSON.parseArray(mouldBoardMsg, MouldBoardMsg.class);
            Integer mouldId = mouldBoardMsgs.get(0).getMouldId();
            Integer proId = mouldBoardMsgs.get(0).getProId();
            TaskStatus taskStatus = taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id", proId)
                    .eq("task_id", 6).eq("status", 0));
            if (ToolUtil.isNotEmpty(taskStatus)) {
                TaskStatusParam param = new TaskStatusParam();
                param.setProId(proId);
                param.setTaskId(6);
                param.setStatus(0);
                taskStatusMapper.deletes(param);
            }
            int taskid = 0;
            int status = 0;
            String taskname = "";
            if (mouldId == 36) {
                taskid = 3;
                status = 1;
            } else if (mouldId == 38) {
                taskid = 2;
                status = 1;
            }//网上建店位置对应的taskid36
            else if (mouldId == 34) {
                taskid = 36;
                status = 0;
            }
            //线上套餐对应的taskid37
            else if (mouldId == 35) {
                taskid = 37;
                status = 0;
            }
            //排队机对应的taskid38
            else if (mouldId == 37) {
                taskid = 38;
                status = 0;
            }
            //现场踏勘对应的taskid30
            else if (mouldId == 39) {
                taskid = 30;
                status = 1;
            }
            //查询是否重复提交
            taskname = taskService.getById(taskid).getName();
            TaskStatus ts = new TaskStatus(proId, taskid, status, "", taskname);
            TaskStatusParam tsparam = new TaskStatusParam(proId, taskid, status, "", taskname, userId);
            boolean exist = taskStatusService.isExist(ts);
            if (exist) {
                return ResponseData.error("已提交，不能重复提交");
            }

            int delete = mouldBoardMsgService.delete(mouldBoardMsgs.get(0).getProId(), mouldBoardMsgs.get(0).getMouldId());


            String con = null;

            boolean save = false;
            for (MouldBoardMsg msg : mouldBoardMsgs
            ) {
                msg.setMouldId(mouldId);
                msg.setProId(proId);
//                if(msg.getPinCode().equals("kfry")){
//                    msg.setData(users.getName());
//                }
//                if(msg.getPinCode().equals("ry")){
//                    msg.setData(users.getPhone());
//                }
                save = mouldBoardMsgService.save(msg);

                //获取现场踏勘图片路径
                if (ToolUtil.isNotEmpty(msg.getPinCode()) && msg.getPinCode().equals("wwztimg")) {
                    con = msg.getData();
                }
            }

            //现场踏勘
            if (taskid == 30) {
                ts = new TaskStatus(proId, taskid, status, con, taskname);
            } else {
                ts = new TaskStatus(proId, taskid, status, "", taskname);
            }


            //现场踏勘
            if (taskid == 30) {
                //当前日期
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                String date = df.format(new Date());

                //当前日期+7
                String seven = DateUtil.addDate(date, 7);
                //当前日期+10
                String ten = DateUtil.addDate(date, 10);
                String con1 = seven + "~" + ten;

                //出图日期
                TaskStatus status1 = new TaskStatus();
                status1.setTaskId(31);
                status1.setProId(proId);
                status1.setStatus(0);
                status1.setTaskName("出图日期");
                status1.setContent(con1);
                status1.setCreateId(userId);

                boolean d = taskStatusService.save(status1);

                //流程明细表
                TaskFlow taskFlow = new TaskFlow();
                taskFlow.setProId(proId);
                taskFlow.setTaskId(31);
                taskFlow.setStatus(0);//1提交；2审核未通过；3审核通过
                taskFlow.setTaskName("出图日期");
                taskFlow.setCreateUser(userId);
                taskFlow.setCreateTime(new Date());

                boolean e = taskFlowService.save(taskFlow);

            }
            boolean b = false;
            int existnum = taskStatusService.selectStau(tsparam);
            if (existnum > 0) {
                int i = taskStatusService.updateAuditSt(tsparam);
                b = (i > 0 ? true : false);
            } else {
                b = taskStatusService.save(ts);
            }


            TaskFlow flow = new TaskFlow();
            flow.setProId(proId);
            flow.setTaskId(taskid);
            flow.setStatus(status);
            flow.setTaskName(taskname);
            flow.setCreateUser(userId);
            boolean c = taskFlowService.save(flow);

            //插入下个节点
            TaskStatusParam taskStatusParam = new TaskStatusParam();
            taskStatusParam.setProId(ts.getProId());
            taskStatusParam.setTaskId(ts.getTaskId());
            taskStatusParam.setCreateUser(ts.getCreateId());
            taskStatusServiceImpl.insertNextNodeH5(taskStatusParam, userId);


            //微信推送
            if (save && b && c) {
                //商务条件
                if (mouldId == 36) {
                    ts.setStatus(BusConst.AUDIT_TODO);
                    projectServiceImpl.pushMsg2KFZJH5(proId, ts, userId);
                    //工程条件
                } else if (mouldId == 38) {
                    ts.setStatus(BusConst.AUDIT_TODO);
                    projectServiceImpl.pushMsg2GCZJH5(proId, ts, userId);
                }
            }
            String dm = taskMapper.selectDm(proId);//店名

            //网上建店/线上套餐/排队机
            if (taskid == 36 || taskid == 37 || taskid == 38) {

                String data = dm + ",督导已提交" + taskname + "!";

                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, taskname, taskname, DateUtil.getNow(), data);

                //网上建店负责人
                Long role = 1307580056085250050L;//网上建店负责人
                List<String> openidlist = userService.listOpenidsByRole(role);

                if (ToolUtil.isNotEmpty(openidlist)) {
                    log.info("=========网上建店负责人:" + openidlist + "========");

                    String[] openids = openidlist.toArray(new String[openidlist.size()]);

                    //推送网上建店负责人
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    log.info("========推送网上建店负责人消息==========");
                }

                //现场踏勘
            } else if (taskid == 30) {
                //工程设计
                Long gcsj = 1373822382028705794L;
                List<String> openidlist = userService.listOpenidsByRole(gcsj);

                if (ToolUtil.isNotEmpty(openidlist)) {
                    log.info("=========工程设计:" + openidlist + "========");

                    //工程设计id
                    List<User> user1 = btyWxMapper.getUser(openidlist);

                    if (ToolUtil.isNotEmpty(user1)) {
                        for (User user : user1) {

                            String[] openids = new String[]{user.getOpenid()};

                            //推送工程设计消息
                            String data = dm + "现场踏勘信息已提交，请及时完成设计图！";
                            log.info("==========现场踏勘信息已提交========");

                            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确认出图日期", "出图日期", DateUtil.getNow(), data);

                            //出图日期url
                            String syUrl = BusConst.WGURL + "&proId=" + proId + "&taskId=31" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            //推送工程设计消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            log.info("=======推送工程设计消息==========");


                            //消息表中新增出图日期消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(proId);//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(31);//任务id
                            gcgMsg.setMsgType("填写出图日期提醒");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(userId);//发送人id
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增出图日期消息
                            gcgMsgMapper.insert(gcgMsg);
                        }
                    }
                }

            }
        } else {
            return ResponseData.error(501, "没有权限新增");
        }

        return ResponseData.success();
    }


    /**
     * 工程条件详情
     * Integer pageA, String gcedit, String auditbtn,String auditbtn1
     * 开发人员 1000
     * 工程总监 1001
     * 开发总监1010
     */
    @RequestMapping("/projectTerm")
    @ResponseBody
    public ResponseData projectTerm(Integer id, HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        //开发人员角色
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        //获取用户信息
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        String flag = selectMsgList(id, 38);
        if (roleList.contains(role_kfry) && flag.equals("[[]]")) {
            map.put("pageA", 1);
            map.put("gcedit", 1);//工程条件可编辑
            map.put("auditbtn", 0);
            map.put("auditbtn1", 0);
        } else {
            map.put("pageA", 1);
            map.put("gcedit", 0);
            map.put("auditbtn", 0);
            map.put("auditbtn1", 0);
        }
        if (roleList.contains(role_gczj)) {
            map.put("pageA", 1);
            map.put("gcedit", 0);
            map.put("auditbtn", 0);
            //工程条件可审核
            map.put("auditbtn1", 1);
        }
        if (roleList.contains(role_kfzj)) {
            map.put("pageA", 1);
            map.put("gcedit", 0);
            //商务条件可审核
            map.put("auditbtn", 1);
            map.put("auditbtn1", 0);
        }
        map.put("id", id);
        map.put("list", selectMsgList(id, 38));
        return ResponseData.success(map);
    }

    /**
     * 商务条件详情
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/things")
    @ResponseBody
    public ResponseData things(Integer id, HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        //开发人员角色
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        //获取用户信息
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        String flag = selectMsgList(id, 36);
        if (roleList.contains(role_kfry) && flag.equals("[[]]")) {
            //商务条件可编辑
            map.put("swedit", 1);
            map.put("auditbtn", 0);
        } else {
            map.put("swedit", 0);
            map.put("auditbtn", 0);
        }
        if (roleList.contains(role_gczj)) {
            map.put("swedit", 0);
            map.put("auditbtn", 0);
        }
        if (roleList.contains(role_kfzj)) {
            map.put("swedit", 0);
            //商务条件可审核
            map.put("auditbtn", 1);
        }
        map.put("id", id);
        map.put("list", selectMsgList(id, 36));
        return ResponseData.success(map);
    }

    /**
     * 查询需填表格列表
     */
    public String selectMsgList(Integer proId, Integer mouldId) {
        ArrayList<MouldBoardMsg> taskStatuses = (ArrayList) projectService.selectMsgList(proId, mouldId);
        String listJson = JSONArray.toJSONString(new ArrayList[]{taskStatuses});
        return listJson;
    }

    /**
     * 工程商务条件审核
     */
    @PostMapping(value = "/audit")
    @ResponseBody
    public ResponseData audit(TaskStatusParam param, HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        //获取用户信息
        Long userId;
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            userId = users.getUserId();
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        } else {
            return ResponseData.error(502, "查不到用户信息");
        }
        if (roleList.contains(role_kfzj) | roleList.contains(role_gczj) | roleList.contains(role_yyzj)) {
            ResponseData responseData = taskStatusServiceImpl.auditH5(param, userId);
            return responseData;
        } else {
            return ResponseData.error(501, "无权限审核");
        }

        //return ResponseData.success();

    }

    /**
     * 添加工程
     */
    @PostMapping(value = "/addItem")
    @ResponseBody
    public ResponseData addItem(ProjectParam projectParam, HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        //开发人员
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();
        //获取用户信息
        Long userId;
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            userId = users.getUserId();
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        } else {
            return ResponseData.error(502, "查不到用户信息");
        }
        //判断工程名称是否重复
        String projectName = projectParam.getName();
        Project project = projectService.getOne(new QueryWrapper<Project>().eq("name", projectName));
        if (ToolUtil.isNotEmpty(project)) {
            return ResponseData.error(1, "店名有重复,可能在此地区已有门店,请尝试在商超/标志性地标前加路名");
        }
        if (roleList.contains(role_kfry)) {
            projectService.addH5(projectParam, userId);
        } else {
            return ResponseData.error(501, "无权限添加工程");
        }

        return ResponseData.success();
    }

    /**
     * 新增任务信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/addRent")
    public ResponseData addRent(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws ParseException {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        //工程部
        Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();
        Long role_gcyq = RoleIdEnum.ROLE_GCYQ.getCode();
        //获取用户信息
        Long userId = null;
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            userId = users.getUserId();
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        if (roleList.contains(role_gcb) | roleList.contains(role_dd)|roleList.contains(role_gcyq)) {
            taskService.addRentH5(taskStatus, userId);
        } else {
            return ResponseData.error(501, "无权限添加");
        }

        return ResponseData.success();
    }

    /**
     * 修改任务信息 确认到货 到货时间修改 预估开业时间修改 卫生许可证修改 宿舍信息修改 开业时间修改 修改门店地址
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/editRent")
    public ResponseData editRent(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws ParseException {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Long> roleList = new ArrayList<>();
        //工程部
        Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();
        //获取用户信息
        Long userId = null;
        User users = userService.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            userId = users.getUserId();
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        if (roleList.contains(role_gcb) | roleList.contains(role_dd)) {
            taskService.editRentH5(taskStatus, userId);
        } else {
            return ResponseData.error(501, "无权限修改");
        }

        return ResponseData.success();
    }


    /**
     * 查询营运经理列表
     *
     * @return
     */
    @RequestMapping(value = "/selectYyjlList")
    @ResponseBody
    public ResponseData selectYyjlList() {
        List<Map> maps = teamService.selectYyjlList();
        return ResponseData.success(maps);
    }

    /**
     * 查询督导列表
     *
     * @return
     */
    @RequestMapping(value = "/selectDdList")
    @ResponseBody
    public ResponseData selectDdList(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        List<Map> maps = teamService.selectDdList(phone);
        return ResponseData.success(maps);
    }

    /**
     * 工程营运经理保存
     */
    @RequestMapping("/saveGcyyjl")
    @ResponseBody
    public ResponseData saveGcyyjl(ProjectParam record, HttpServletRequest request) {
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();
        //获取用户角色
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        User user = userService.getAccount(phone);
        List<Long> roleList = new ArrayList<>();
        Long userId = null;
        if (ToolUtil.isNotEmpty(user)) {
            userId = user.getUserId();
            String[] roles = user.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        if (roleList.contains(role_yyzj)) {
            String[] errwords = {"消息通知", "消息通知", DateUtil.getNow(), ""};
            if (ToolUtil.isOneEmpty(record, record.getId(), record.getYyjl())) {
                return ResponseData.error(400, "请求有错误");
            }
            Project pro = projectService.getById(record.getId());
            String oldyyjl = pro.getYyjl();
            String name = record.getYyjl();
            String tel = record.getTel().trim();
            if (ToolUtil.isNotEmpty(oldyyjl) && oldyyjl.equals(tel)) {//如果两次人相同，不再处理
            }

            String userName = null;
            if (ToolUtil.isEmpty(record.getCreateUser())) {
                User users = userService.getById(userId);
                if (ToolUtil.isNotEmpty(users)) {
                    userName = users.getName();
                }
            } else {
                userId = record.getCreateUser();
                userName = userMapper.getName(record.getCreateUser());
            }

            Map<String, Object> wx = userService.getWxByUserid(userId);
            if (ToolUtil.isEmpty(wx)) {
                log.error("未获取到营运总监-{} 微信的openid,userid={}", userName, userId);

            }
            String yyzjopenid = "";
            if (ToolUtil.isNotEmpty(wx)) {
                yyzjopenid = wx.get("openid") == null ? "" : wx.get("openid").toString();
            }
            List<BtyWx> wxs = btyWxService.getWx(tel);
            //营运经理
            List<String> openidlist = getOpenids(wxs);
            if (ToolUtil.isEmpty(openidlist)) {
                log.error("{},营运经理-{}", BusExceptionEnum.NO_WX.getMessage(), name);
                errwords[3] = "指定营运经理失败：" + BusExceptionEnum.NO_WX.getMessage();
                JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
                //报错时，推送给营运总监失败
                weChatSendTempMsgService.sendmsg(yyzjopenid.split(","), BusConst.MSURL, errparam);
                return ResponseData.error(2002, "查无此人，请确认手机号是否一致且已绑定部门");
            }

            if (ToolUtil.isEmpty(record.getTel())) {
                log.error("营运经理-{}未绑定手机!", record.getYyjl());
                errwords[3] = "指定营运经理失败：" + name + "-" + BusExceptionEnum.NO_PHONE.getMessage();
                JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
                //报错时，推送给营运总监失败
                weChatSendTempMsgService.sendmsg(yyzjopenid.split(","), BusConst.MSURL, errparam);
                //throw new BusException(BusExceptionEnum.NO_PHONE);
                return ResponseData.error(2001, "此人档案不存在，请联系孙娇添加档案");
            }
            record.setYyjl(tel);
            record.setUpdateTime(new Date());
            int i = projectMapper.updateProjectByCondition(record);
            if (i > 0) {
                //保存taskstatus
                TaskStatusParam ts = new TaskStatusParam();
                ts.setProId(record.getId());
                ts.setTaskId(40);
                ts.setStatus(1);
                if (ToolUtil.isNotEmpty(record.getCreateUser())) {
                    ts.setCreateUser(record.getCreateUser());
                }
                int tsExist = taskStatusService.selectStau(ts);
                if (tsExist == 0) {
                    taskStatusService.addH5(ts, userId);
                } else {
                    taskStatusService.updateAuditSt(ts);
                }

                //保存flow
                TaskFlowParam flow = new TaskFlowParam();
                flow.setProId(record.getId());
                flow.setTaskId(40);
                flow.setStatus(1);
                if (ToolUtil.isNotEmpty(record.getCreateUser())) {
                    flow.setCreateUser(record.getCreateUser());
                } else {
                    flow.setCreateUser(userId);
                }
                taskFlowService.addH5(flow, userId);
                taskStatusService.insertNextNodeH5(ts, userId);//插入下个节点

                //修改通讯录营运经理
                if (ToolUtil.isNotEmpty(pro.getYaoma())) {
                    BtyTxl btyTxl = new BtyTxl();
                    btyTxl.setYytel(tel);
                    btyTxl.setYyjlqy(name);
                    btyTxl.setCtbh(pro.getYaoma());
                    btyTxlMapper.updateTxlYy(btyTxl);
                }

                //推送营运经理通知
                String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "已指定您为该店营运经理，请指定督导"};
                JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ",请指定督导！", strs);


                String[] openids = openidlist.toArray(new String[openidlist.size()]);

                //营运经理
                List<User> user1 = btyWxMapper.getUser(openidlist);
                if (ToolUtil.isNotEmpty(user1)) {
                    for (User users : user1) {
                        //指定督导
                        String syUrl = BusConst.DDURL + "&proId=" + record.getId() + "&taskId=41" + "&userId=" + users.getUserId();
                        String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                        //推送营运经理消息
                        weChatSendTempMsgService.sendmsg(openids, url, param);
                        log.info("=======营运经理已保存'通知并推送给营运经理-{}==========");

                        //消息表中新增推送指定营运经理消息
                        GcgMsg gcgMsg = new GcgMsg();
                        gcgMsg.setBusinessId(record.getId());//业务id
                        gcgMsg.setBusinessType("工程");//业务类型
                        gcgMsg.setBusinessName(pro.getName());//业务名称
                        gcgMsg.setTaskId(40);//任务id
                        gcgMsg.setMsgType("指定营运经理提醒");//消息类型
                        gcgMsg.setMessage(Arrays.toString(strs));//消息内容
                        gcgMsg.setPath(url);//跳转路径
                        gcgMsg.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                        if (ToolUtil.isNotEmpty(record.getCreateUser())) {
                            gcgMsg.setSendUser(record.getCreateUser());//发送人id
                        } else {
                            gcgMsg.setSendUser(userId);//发送人id
                        }
                        gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                        gcgMsg.setCreateTime(new Date());//创建时间

                        //消息表新增出图日期消息
                        msgMapper.insert(gcgMsg);
                    }
                }

                if (tsExist > 0) {
                    //推送给旧的营运经理
                    List<BtyWx> oldwxs = btyWxService.getWx(oldyyjl);
                    List<String> oldopenidList = getOpenids(oldwxs);
                    String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                    String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,营运经理已变更为" + name};
                    JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), "由你负责的店,营运经理已变更为" + name, oldstrs);
                    weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
                }
                //推送给开发人员 yyjl的信息
                Map<String, Object> kfrywx = userService.getWxByUserid(pro.getCreateUser());
                if (ToolUtil.isEmpty(kfrywx)) {
                    log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
                }
                String openid = (String) kfrywx.get("openid");
                String[] os = {openid};
                String[] str2 = {"消息通知", "消息通知", DateUtil.getNow(), "该工程已分派营运经理"};
                JSONObject kfryjs = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), "营运经理：" + name + ",电话：" + tel, str2);
                weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, kfryjs);
                log.info("'营运经理已保存'通知并推送给{}", name);


                //刘书伟
                String[] openidsLiu = new String[]{BusConst.LSW};
                String data = pro.getName() + "已确定开店，请确认店名是否合适！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), null, "消息通知", "消息通知", DateUtil.getNow(), data);
                //推送消息
                weChatSendTempMsgService.sendmsg(openidsLiu, BusConst.MSURL, tempObj);
                log.info("=======推送收刘书伟消息==========");
            }
        } else {
            return ResponseData.error(501, "无权限");
        }

        return ResponseData.success();
    }

    /**
     * 工程督导保存
     */
    @RequestMapping("/saveGcDd")
    @ResponseBody
    public ResponseData saveGcDd(ProjectParam record, HttpServletRequest request) {
        Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();
        //获取用户角色
        String phone = request.getParameter("phone");
        //        String token=request.getHeader("token");
//        if(ToolUtil.isEmpty(token)){
//            return ResponseData.error(501, "无权限操作");
//        }
        User user = userService.getAccount(phone);
        List<Long> roleList = new ArrayList<>();
        Long userId = null;
        if (ToolUtil.isNotEmpty(user)) {
            userId = user.getUserId();
            String[] roles = user.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        if (roleList.contains(role_yyjl)) {
            if (ToolUtil.isOneEmpty(record, record.getId(), record.getDd())) {
                //throw new ServiceException(BizExceptionEnum.REQUEST_NULL);//请求有错误
                return ResponseData.error(506, "请求有错误");
            }
            boolean isexist = isexist(record.getId(), ProjectTaskEnum.TASK_40.getCode().toString());
            if (!isexist) {
                //throw new ServiceException(BusExceptionEnum.ERR_NO_YYJLOK);
                return ResponseData.error(505, "营运经理未指定");
            }
            Project pro = projectMapper.selectById(record.getId());
            String olddd = pro.getDd();

            String name = record.getDd();
            String tel = record.getTel().trim();
            List<BtyWx> wxss = btyWxMapper.getWx(tel);
            List<String> openidlists = getOpenids(wxss);
            if (ToolUtil.isEmpty(openidlists)) {
                return ResponseData.error(2002, "查无此人，请确认手机号是否一致且已绑定部门");
            } else {
                if (ToolUtil.isNotEmpty(olddd) && olddd.equals(tel)) {//如果两次人相同，不再处理
                    return ResponseData.error(507, "督导相同，无需重复保存");
                }
                if (ToolUtil.isEmpty(record.getTel())) {
                    return ResponseData.error(2001, "此人档案不存在，请联系孙娇添加档案");
                }
                record.setDd(tel);
                record.setUpdateTime(new Date());
                int i = projectMapper.updateProjectByCondition(record);

                //Long userId;
                if (ToolUtil.isNotEmpty(record.getCreateUser())) {
                    userId = record.getCreateUser();
                }

                if (i > 0) {
                    //保存taskstatus
                    TaskStatusParam ts = new TaskStatusParam();
                    ts.setProId(record.getId());
                    ts.setTaskId(ProjectTaskEnum.TASK_41.getCode());
                    ts.setStatus(1);
                    ts.setCreateUser(userId);
                    int tsExist = taskStatusService.selectStau(ts);
                    if (tsExist == 0) {
                        taskStatusService.add(ts);
                    } else {
                        taskStatusService.updateAuditSt(ts);
                    }

                    //保存flow
                    TaskFlowParam flow = new TaskFlowParam();
                    flow.setProId(record.getId());
                    flow.setTaskId(ProjectTaskEnum.TASK_41.getCode());
                    flow.setStatus(1);
                    flow.setCreateUser(userId);
                    taskFlowService.add(flow);
                    taskStatusService.insertNextNode(ts);//插入下个节点

                    //修改通讯录督导
                    if (ToolUtil.isNotEmpty(pro.getYaoma())) {
                        BtyTxlRY btyTxlRY = new BtyTxlRY();
                        btyTxlRY.setLxfs(tel);
                        btyTxlRY.setFzr(name);
                        btyTxlRY.setZw("督导");
                        btyTxlRY.setSsctbh(pro.getYaoma());
                        btyTxlMapper.updateTxlRYDd(btyTxlRY);
                    }


                    //推送督导通知
                    String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "您有新的开新店任务"};
                    System.out.println(Arrays.toString(strs) + "''''''''''''");
                    JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ":您有新的开新店任务！", strs);
                    if (tsExist > 0) {
                        //修改督导后推送旧督导通知
                        List<BtyWx> oldwxs = btyWxMapper.getWx(olddd);
                        List<String> oldopenidList = getOpenids(oldwxs);
                        String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                        String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,督导已变更为" + name};
                        JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), "由你负责的店,督导已变更为" + name, oldstrs);
                        weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
                    }


                    //督导
                    List<BtyWx> wxs = btyWxMapper.getWx(tel);
                    List<String> openidlist = getOpenids(wxs);
                    if (ToolUtil.isEmpty(openidlist)) {
//                log.error("{},督导-{}", BusExceptionEnum.NO_WX.getMessage(), name, BusExceptionEnum.NO_WX.getCode());
                        //throw new BusException(BusExceptionEnum.NO_WX);
                        return ResponseData.error(2002, "查无此人，请确认手机号是否一致且已绑定部门");
                    }

                    //督导id
                    List<User> userList = btyWxMapper.getUser(openidlist);
                    if (ToolUtil.isNotEmpty(userList)) {
                        for (User user1 : userList) {

                            //查询是否开工
                            int count = taskMapper.getRent(record.getId(), 32);
                            //无开工日期
                            if (count == 0) {
                                //无开工日期提醒页面url
                                String bdUrl = BusConst.KGURL + "&proId=" + record.getId() + "&userId=" + user1.getUserId();
                                String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                                String[] openid = new String[]{user1.getOpenid()};

                                //推送消息（无开工日期提醒页面）
                                weChatSendTempMsgService.sendmsg(openid, url1, param);

                                //消息表中新增指定督导消息
                                GcgMsg gcgMsg2 = new GcgMsg();
                                gcgMsg2.setBusinessId(record.getId());//业务id
                                gcgMsg2.setBusinessType("工程");//业务类型
                                gcgMsg2.setBusinessName(pro.getName());//业务名称
//                    gcgMsg2.setTaskId(19);//任务id
                                gcgMsg2.setMsgType("指定督导提醒");//消息类型
                                gcgMsg2.setMessage(Arrays.toString(strs));//消息内容
                                gcgMsg2.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                                if (ToolUtil.isEmpty(record.getCreateUser())) {
                                    gcgMsg2.setSendUser(userId);//发送人id
                                } else {
                                    gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                                }
                                gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                                gcgMsg2.setCreateTime(new Date());//创建时间
                                gcgMsg2.setPath(url1);//跳转路径

                                //消息表新增指定督导消息
                                msgMapper.insert(gcgMsg2);

                            } else {
                                //本店任务页面url
                                String bdUrl = BusConst.BDURL + "&proId=" + record.getId() + "&userId=" + user1.getUserId();
                                String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                                String[] openid = new String[]{user1.getOpenid()};

                                //推送消息（本店任务页面）
                                weChatSendTempMsgService.sendmsg(openid, url1, param);

                                //消息表中新增指定督导消息
                                GcgMsg gcgMsg2 = new GcgMsg();
                                gcgMsg2.setBusinessId(record.getId());//业务id
                                gcgMsg2.setBusinessType("工程");//业务类型
                                gcgMsg2.setBusinessName(pro.getName());//业务名称
//                    gcgMsg2.setTaskId(19);//任务id
                                gcgMsg2.setMsgType("指定督导提醒");//消息类型
                                gcgMsg2.setMessage(Arrays.toString(strs));//消息内容
                                gcgMsg2.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                                if (ToolUtil.isEmpty(record.getCreateUser())) {
                                    gcgMsg2.setSendUser(userId);//发送人id
                                } else {
                                    gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                                }
                                gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                                gcgMsg2.setCreateTime(new Date());//创建时间
                                gcgMsg2.setPath(url1);//跳转路径

                                //消息表新增指定督导消息
                                msgMapper.insert(gcgMsg2);


                                //查询开工日期
                                String time = taskMapper.getCon(record.getId(), 32);
                                //刘书伟
                                String syxt = BusConst.LSW;
                                String[] openids = new String[]{syxt};
                                //收银系统负责人 (刘书伟)id
                                User users = btyWxMapper.selectUser(syxt);
                                Map<String, String> openidMap = projectService.selectDd(record.getId());
                                String ddName = openidMap.get("ddName");
                                String ddTel = openidMap.get("ddTel");
                                //推送收银系统确认消息
                                String data = pro.getName() + "已确定开工日期为:" + time + ",请确认收银系统。该店督导为：" + ddName + "电话为:" + ddTel;

                                JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), null, "确认收银系统", "收银系统", DateUtil.getNow(), data);

                                if (ToolUtil.isNotEmpty(users)) {
                                    //收银系统url（负责人）
                                    String syUrl = BusConst.SYURL + "&proId=" + record.getId() + "&taskId=21" + "&userId=" + users.getUserId();
                                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                                    //推送收银系统消息
//                            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                                    weChatSendTempMsgService.sendmsg(openids, url, tempObj);

                                    //消息表中新增收银系统消息
                                    GcgMsg gcgMsg = new GcgMsg();
                                    gcgMsg.setBusinessId(record.getId());//业务id
                                    gcgMsg.setBusinessType("工程");//业务类型
                                    gcgMsg.setBusinessName(pro.getName());//业务名称
                                    gcgMsg.setTaskId(21);//任务id
                                    gcgMsg.setMsgType("确认收银系统提醒");//消息类型
                                    gcgMsg.setMessage(data);//消息内容
                                    gcgMsg.setPath(url);//跳转路径
                                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                    if (ToolUtil.isEmpty(record.getCreateUser())) {
                                        gcgMsg2.setSendUser(userId);//发送人id
                                    } else {
                                        gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                                    }
                                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                    gcgMsg.setCreateTime(new Date());//创建时间

                                    //消息表新增收银系统数据
                                    msgMapper.insert(gcgMsg);
                                }
                            }

                        }
                    }
                }
            }
        } else {
            return ResponseData.error(501, "无权限");
        }

        return ResponseData.success();
    }

    private List<String> getOpenids(List<BtyWx> wxs) {
        List<String> list = new ArrayList<>();
        for (BtyWx wx : wxs) {
            if (ToolUtil.isNotEmpty(wx.getOpenid())) {
                list.add(wx.getOpenid());
            }
        }
        return list;
    }

    private boolean isexist(Integer proId, String taskids) {
        String[] split = taskids.split(",");
        List<TaskStatus> list = taskStatusService.listBytaskids(proId, taskids);
        if (list.size() == split.length) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 工程流程页面
     */
    @RequestMapping("/projectTask")
    @ResponseBody
    public ResponseData projectTask(Integer id, ModelMap map) {
        map.put("list", taskList(id));
        return ResponseData.success(map);
    }

    /**
     * 督导/工程部任务数据
     */
    public String taskList(Integer proId) {
        ArrayList<TaskStatus> taskStatuses = (ArrayList) taskService.taskList(proId);
        String listJson = JSONArray.toJSONString(new ArrayList[]{taskStatuses});
        return listJson;
    }


    private boolean isexist2(List<TaskStatus> taskStatusList, String taskids) {
        if (!CollectionUtil.isNotEmpty(taskStatusList) && !StringUtils.isEmpty(taskids)) {
            return false;
        }

        List<Integer> taskStatusIdList = taskStatusList.stream().map(TaskStatus::getTaskId).collect(Collectors.toList());

        String[] taskidsArr = taskids.split(",");
        int[] array = Arrays.stream(taskidsArr).mapToInt(Integer::parseInt).toArray();
        List<Integer> taskidsList = Arrays.stream(array).boxed().collect(Collectors.toList());
        //取交集-获取taskStatusList中taskids的数据
        taskidsList.retainAll(taskStatusIdList);
        if (taskidsList.size() == taskidsArr.length) {
            return true;
        } else {
            return false;
        }
    }

    private List<TaskStatus> getTaskStatusListByTaskIds(List<TaskStatus> taskStatusList, String taskids) {
        List<TaskStatus> list = new ArrayList<>();
        String[] split = taskids.split(",");
        for (int i = 0; i < split.length; i++) {
            for (TaskStatus taskStatus : taskStatusList) {
                if (taskStatus.getTaskId() == Integer.parseInt(split[i])) {
                    list.add(taskStatus);
                }
            }
        }
        return list;
    }

    /**
     * 查询开发人员工程列表
     * @return
     */
    @RequestMapping(value = "/selectKfryList")
    @ResponseBody
    public ResponseData selectKfryList(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        Map<String, Object> map = new HashMap<>();
         //通过userId获取开发人员的所有工程
        ProjectParam param=new ProjectParam();
        if(ToolUtil.isNotEmpty(userId)){
            param.setCreateUser(Long.valueOf(userId));
        }else{
            param.setCreateUser(111L);
        }

        List<ProjectResult>resultList=projectMapper.kfryList(param);
        Integer count = resultList.size();
        map.put("list", resultList);
        map.put("count", count);
        return ResponseData.success(map);
    }


}
